러스트에서는 열거형 (enum)은 단순한 목록을 넘어서는 존재입니다. 그것은 가능성의 구조 설계도와 같습니다. 느슨하게 그룹화된 정수와 달리, 열거형은 합집합 타입이라는 의미로, 변수가 여러 개의 서로 다른 변형중 하나만 나타낼 수 있다는 것을 의미합니다.
1. 네임스페이싱 및 범위
변형들은 두 콜론(::) 연산자를 사용해 열거형 식별자 아래에 깔끔하게 배치됩니다. 이 네임스페이싱 은 서로 다른 모듈, 크레이트또는 패키지간의 충돌을 방지합니다. 이를 통해 다양한 맥락에서 V4 변형을 명확하지 않은 상태로 정의할 수 있습니다.
2. 타입 안전성
함수 인수로 열거형을 사용함으로써, 표준 라이브러리 패턴은 유효한 상태만 로직 내부로 들어오도록 보장합니다. 이는 잠재적인 런타임 오류를 컴파일 시점으로 옮기며, 당신의 route 함수가 존재하지 않는 "v5" 주소를 처리해야 할 필요가 없음을 보장합니다.
main.py
TERMINALbash — 80x24
> Ready. Click "Run" to execute.
>
QUESTION 1
Which operator is used to access a variant within an enum's namespace?
The dot operator (
.)The double colon (
::)The arrow operator (
->)The ampersand (
&)✅ Correct!
Correct! The double colon links the enum type to its specific variant scope.❌ Incorrect
Rust uses the double colon (::) for namespacing variants under their enum identifier.QUESTION 2
Why are enums considered 'Type Safe' in function arguments?
They allow any integer to be passed as long as it is positive.
They force the compiler to check that only predefined variants are used.
They automatically encrypt the data.
They convert strings to integers automatically.
✅ Correct!
Exactly. The compiler guarantees that only legitimate variants can be passed, eliminating invalid input cases.❌ Incorrect
Enums restrict values to a predefined set, catching errors during compilation rather than at runtime.QUESTION 3
In the IP address example, what is the primary benefit of using an enum over a String?
Strings use less memory.
Strings are easier to type.
Enums eliminate the need for 'invalid version' error handling in the function body.
Enums allow for infinite variants.
✅ Correct!
Because the type is constrained to V4 or V6, the function logic is simplified.❌ Incorrect
Using Strings requires manual validation; Enums provide validation through the type system itself.QUESTION 4
What happens if you try to use a variant name that hasn't been defined in the enum?
The program crashes at runtime.
The compiler throws a 'variant not found' error.
Rust creates the variant automatically.
It defaults to the first variant.
✅ Correct!
Correct. Rust is strict about its defined types within a scope.❌ Incorrect
Rust's compiler ensures that every identifier used matches a known definition in the current scope.QUESTION 5
Can two different enums in the same module have variants with the same name?
No, it causes a naming conflict.
Yes, because they are namespaced under their respective enum identifiers.
Only if they are inside a struct.
Only if one is private.
✅ Correct!
Yes! Color::Red and Stoplight::Red are distinct because of namespacing.❌ Incorrect
Namespacing allows the same variant name to exist across different types without conflict.Module Architecture Case Study
Applying Enums to API Design
You are designing a cross-platform file system library. You need to represent the status of a file operation: Success, Failure (with an error code), or Pending. You are deciding between using a set of constants or a single Enum.
Q
How does using an Enum improve the maintainability of your API across different Crates?
Solution:
Using an Enum ensures that any external user of the Crate is forced to handle the specific variants you've defined. It provides a single source of truth for possible states, and namespacing prevents these states from conflicting with the user's local variables.
Using an Enum ensures that any external user of the Crate is forced to handle the specific variants you've defined. It provides a single source of truth for possible states, and namespacing prevents these states from conflicting with the user's local variables.
Q
What is the architectural advantage of Namespacing in this scenario?
Solution:
Namespacing allows you to use clear, concise names like
Namespacing allows you to use clear, concise names like
Status::Pending without worrying that 'Pending' is already used as a variable name in the main program. It encapsulates the logic within the type's own scope.